package tree.rightview;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * https://leetcode-cn.com/problems/binary-tree-left-side-view/
 * 二叉树左视角
 * <p>
 * 给定一个二叉树的 根节点 root，想象自己站在它的左侧，按照从顶部到底部的顺序，返回从左侧所能看到的节点值。
 *
 * @author xushijian
 * @date 2021/08/12 8:42
 */
public class LeftSideView {

    public static void main(String[] args) {
        //1,2,3,null,null,4,5
        TreeNode treeNode = new TreeNode(1);
        treeNode.left = new TreeNode(2);
        treeNode.right = new TreeNode(3);
        treeNode.left.left = new TreeNode(4);
        //treeNode.right.right = new TreeNode(5);


        System.out.println(new LeftSideView().leftSideView(treeNode));
    }

    /**
     * 每一层最左边节点 1,2,3,null,null,4,5
     *
     * @param root 树
     * @return 集合
     */
    public List<Integer> leftSideView(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        boolean findLeft;
        while (!queue.isEmpty()) {
            //只处理当前层级 (随节点数变化的）
            int size = queue.size();
            findLeft = false;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (!findLeft) {
                    ret.add(node.val);
                    findLeft = true;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return ret;
    }
}
//
//class TreeNode {
//    int val;
//    TreeNode left;
//    TreeNode right;
//
//    TreeNode(int x) {
//        val = x;
//    }
//
//}

// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// TreeNode ans = deser.deserialize(ser.serialize(root));
//分析： 1. 考查树存储结构       -----> 用List<TreeNode> 存储带有子节点的各节点
//      2. 遍历、取值